package com.gitee.hermer.engine.jars.core.xa.transaction.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.jta.JtaTransactionManager;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.engine.jars.core.xa.transaction.config.XATransactionProperties;
import com.gitee.hermer.engine.jars.dependent.dsm.IEnginePropertiesAware;

@Configuration
@EnableTransactionManagement
public class EngineJarsXATransactionAutoConfiguration extends UtilsContext implements IEnginePropertiesAware<XATransactionProperties>{
	
	
	private XATransactionProperties properties;

	@Bean(destroyMethod="close",initMethod="init")
	public UserTransactionManager getUserTransactionManager(){
		UserTransactionManager manager = new UserTransactionManager();
		manager.setForceShutdown(true);
		return manager;
	}
	
	@Bean()
	public UserTransactionImp getUserTransactionImp(){
		try{
			UserTransactionImp imp = new UserTransactionImp();
			imp.setTransactionTimeout(properties.getTranTimeOut());
			return imp;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Bean
	public PlatformTransactionManager getJtaTransactionManager(UserTransactionManager transactionManager,UserTransactionImp transaction){
		JtaTransactionManager manager = new JtaTransactionManager();
		manager.setTransactionManager(transactionManager);
		manager.setUserTransaction(transaction);
		manager.setAllowCustomIsolationLevels(properties.getAllowCustomIsolationLevels());
		manager.setGlobalRollbackOnParticipationFailure(properties.getRollbackOnParticipationFailure());
		return manager;
	}

	@Override
	@Autowired
	public void setProperties(XATransactionProperties properties) {
		this.properties = properties;
	}
}
